<template>
  <div class="content">
    <a-tabs class="tabRight fixed" size="small" :tabBarGutter="0" v-model="activeKey" @change="onTabChange">
      <div slot="tabBarExtraContent">
        <a-button icon="reload" @click="onRefresh">刷新</a-button>
        <a-divider type="vertical" />
        <a-button type="primary" icon="plus" @click="onAddBtnClick">新增</a-button>
        <a-button type="danger" icon="fa fa-remove" @click="onDeleteBtnClick">删除</a-button>
      </div>
      <a-tab-pane v-for="item in tabPanels" :key="item.key" :tab="item.text">
        <keep-alive>
          <component :is="item.key" :ref="item.key" @refresh="onRefresh" :toolbarHidden="true" />
        </keep-alive>
      </a-tab-pane>
    </a-tabs>
  </div>
</template>

<script>
import aaa from '@/views/archives/psrs/LineCrud';
export default {
  name: 'tabpanel',
  components: { aaa },
  props: {
    tabItems: {
      type: Array,
      required: true,
      default: () => []
    }
  },

  data() {
    return {
      // 被授权显示的tab页，结构与 tabItems一致
      tabPanels: [],
      activeKey: null
    };
  },
  mounted() {
    this.initTabItems();
  },
  methods: {
    /** 初始化所有tabItem，以供显示 */
    initTabItems() {
      let operations = [];
      this.tabItems.forEach(element => {
        operations.push(
          import(`@/views/${element.view}.vue`).then(cmp => {
            this.$options.components[element.key] = cmp.default;
          })
        );
      });
      Promise.all(operations).then(res => {});
    },
    onTreeSelect(treeNode) {
      this.tabPanels = this.tabItems.filter(x => x.authClz.includes(treeNode.clz));
      // 如果当前active处在权限外，或者当前active为空，则应重新选举active
      if (!this.tabPanels.map(x => x.key).includes(this.activeKey) || !this.activeKey) {
        if (this.tabPanels && this.tabPanels.length > 0) {
          this.activeKey = this.tabPanels[0].key;
        } else {
          this.activeKey = null;
        }
      }
    },
    onRefresh() {
      this.$nextTick(() => {
        let activeCmp = this.getActivePage();
        activeCmp && activeCmp.refresh && activeCmp.refresh();
      });
    },
    onAddBtnClick() {
      let activeCmp = this.getActivePage();
      activeCmp && activeCmp.add && activeCmp.add();
    },
    onDeleteBtnClick() {
      let activeCmp = this.getActivePage();
      activeCmp && activeCmp.delete && activeCmp.delete();
    },
    onTabChange(activeKey) {
      this.onRefresh();
    },
    getActivePage() {
      let activeCmps = this.activeKey && this.$refs[this.activeKey];
      if (activeCmps && activeCmps.length > 0) {
        return activeCmps[0];
      }
      return null;
    }
  }
};
</script>

<style lang="less" scoped>
.content {
  padding: 0px;
  min-width: 1100px;
  height: 100%;
}

.fixed {
  height: 100%;
}
</style>
